<?php
namespace Home\Controller;
use Think\Controller;
class BbqmDLController extends Controller {
    public function index(){
        indexRvent();//测算首页执行事件
        $this->assign('titleName',titleName('Bbqm',1));//首页名称
        indexRequest($_REQUEST);//测算首页接收数据处理

        //redirect(U('Bbqm/index','',false));

        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            getToken();
            getTicket();
            $wzurl=wxJsdkData();

            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            getCode($wzurl);
            getOopenid();
            cookie('uid',cookie('openid'));
        }

        if(cookie('jploginHC')==''){
            cnzz_pvuv('BBQM');//执行统计
            cookie('jploginHC',1,30);
            //宝宝起名随机数
            csRandNum('bbqmcs',500000,599999);
        }

        $this->display('BbqmDL/ZM_bbqmDL');

    }
    public function bbqm_zhifu(){
        $this->assign('titleName',titleName('Bbqm',2));//首页名称
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            $this->assign('wxlogin',cookie('wxlogin'));
            getToken();
            getTicket();
            $wzurl=wxJsdkData();

            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            getCode($wzurl);
            getOopenid();
        }

        if($_REQUEST['username']){//返回操作
            cookie('znickname',I('post.username'),604800);
            cookie('zymd',mb_substr($_REQUEST['birthday'],2,10),7200);
            cookie('zhour',mb_substr($_REQUEST['birthday'],13,2),7200);
            cookie('zsex',$_REQUEST['gender'],604800);
            cookie('datetype',mb_substr($_REQUEST['birthday'],0,1));
            $phone=$_REQUEST['phone'];
            $setmealName=$_REQUEST['setmeal'];
            if($setmealName=='一举成名套餐'){
                $setmeal=1;cookie('price',198);//价格
            }else{
                $setmeal=2;cookie('price',398);
            }
        }

        if(!empty($_REQUEST['ordernum'])){//未支付订单
            $arrdata=M()->query("select * from sm_h5test where ordernum='{$_REQUEST['ordernum']}'");
            $zymd=$arrdata[0]['year'].'-'.str_pad($arrdata[0]['month'],2,"0",STR_PAD_LEFT).'-'.str_pad($arrdata[0]['day'],2,'0',STR_PAD_LEFT);
            cookie('zymd',$zymd,604800);
            cookie('zhour',$arrdata[0]['hour'],604800);
            cookie('znickname',$arrdata[0]['username'],604800);
            cookie('zsex',$arrdata[0]['sex'],604800);
            cookie('datetype',$arrdata[0]['datetype']);
            cookie('orderid',$_REQUEST['ordernum']);
        }

        $data=cookie('orderid');//获取订单号
        if(empty($data)&&empty($_REQUEST['ordernum'])){
            $orderid='BBQM'.date('Ymd').mt_rand(1000,9999).date('His');
            cookie('orderid',$orderid);
        }

        //创建订单
        $hour=cookie('zhour');
        $shop=cookie('orderid');
        $znickname=cookie('znickname');if($znickname=='')$znickname='匿名';
        $zsex=cookie('zsex');if($zsex=='')$zsex=1;
        $channel=cookie('channel');
        $imei=cookie('uid');if(cookie('uid')==''){$imei=cookie('imei');}
        $y=mb_substr(cookie('zymd'),0,4);//年
        $m=mb_substr(cookie('zymd'),5,2); //月
        $d=mb_substr(cookie('zymd'),8,2);//日
        $datetype=cookie('datetype');if($datetype=='')$datetype=0;

//        $channelPayArr=M()->query("select pay from tb_channel_pay where channel='{$channel}' limit 1");//查询渠道价格
//        if($channelPayArr){cookie('price',$channelPayArr[0]['pay']);}

        $datastr=stristr(cookie('znickname'),'测试');
        if($datastr){cookie('price',0.01);}

        $price=cookie('price');
        if(empty($_REQUEST['ordernum'])){
            $arrdata=M()->query("select id from sm_h5test_bbqm where ordernum='{$shop}' limit 1");
            if(empty($arrdata)){
                M()->query("insert into sm_h5test_bbqm (ordernum,price,username,typeid,sex,status,datetype,year,month,day,hour,paykind,date_remark,appuserid,ip,channel,phone,set_meal)values(
                                              '{$shop}','{$price}','{$znickname}',28,{$zsex},-1,'{$datetype}',{$y},{$m},{$d},{$hour},-1,'{$imei}','{$imei}','{$_SERVER['REMOTE_ADDR']}','{$channel}','{$phone}','{$setmeal}')");
            }
            if(!cookie($_REQUEST['username'])){//返回操作
                //更新订单
                M()->query("update sm_h5test_bbqm set price='{$price}',username='{$znickname}',datetype='{$datetype}',year={$y},month={$m},day={$d},sex={$zsex} where ordernum='{$shop}'");
            }
        }

        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
        }else{
            //$xml=wxgzhzf('QM','宝宝起名',cookie('orderid'));//公众号支付回调参数
            $xml=$this->wxgzhzf('BBQM','宝宝起名',cookie('orderid'));
            $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
            $val = json_decode(json_encode($xmlstring),true);
            $noncestr=noncestr(15);//随机字符串
            $timestamp=time();//时间戳
            $stringA="appId=".cookie('APPID')."&nonceStr={$noncestr}&package=prepay_id={$val['prepay_id']}&signType=MD5&timeStamp={$timestamp}";
            $stringSignTemp=$stringA."&key=".cookie('wxKEY');
            $sign=strtoupper(md5($stringSignTemp));

            $this->assign('timeStamp',$timestamp);
            $this->assign('nonceStr',$noncestr);
            $this->assign('package','prepay_id='.$val['prepay_id']);
            $this->assign('signType','MD5');
            $this->assign('paySign',$sign);
            $this->assign('appId',cookie('APPID'));
        }

        $this->display('BbqmDL/ZM_bbqm_zhifuDL');
    }
    public function jieguoye(){//
        $this->assign('titleName',titleName('Bbqm',3));//首页名称
        $this->display("BbqmDL/ZM_bbqm_zhifu_jieguoyeDL");
    }
    public function mycesuan(){//
        $user_agent = $_SERVER['HTTP_USER_AGENT'];//用户使用的浏览器，操作系统等信息。
        if (strpos($user_agent, 'MicroMessenger') == false) {
            //非微信浏览器访问
            cookie('wxlogin',0);
        }else{
            cookie('wxlogin',1);
            getToken();
            getTicket();
            $wzurl=wxJsdkData();
            if(!empty($_REQUEST['code'])){
                cookie('code',$_REQUEST['code'],7100);
            }
            getCode($wzurl);
            getOopenid();
            cookie('uid',cookie('openid'));
        }
        $uid=cookie('uid');
        if($uid!=''){
            $arr=M()->query("select ordernum,username,typeid,status from sm_h5test_bbqm where price > 0 and appuserid ='{$uid}' and status=1 order by status desc,id desc limit 10");
        }
        $this->assign('arr',$arr);
        $this->display("BbqmDL/ZM_mycesuan");
    }

    public function pay(){
        $this->assign('ordername1','宝宝起名');
        $this->assign('ordername2','知命-宝宝起名');
        $this->display("BbqmDL/pay");
    }
    public function paywx(){
        $nick='BBQM';$name='宝宝起名';$orderid=cookie('orderid');$csName='BbqmDL';
        if(empty($nick)){echo 'nike';exit;}
        $arrdata=M()->query("select id from sm_h5test_bbqm where ordernum='{$orderid}' and status=-1 limit 1");
        if(!empty($arrdata)){
            if(cookie('wxzfNum')!=''){
                $orderid=$nick.date('Ymd').mt_rand(1000,9999).date('His');//重新生成订单
                cookie('orderid',$orderid);
                M()->query("update sm_h5test_bbqm set ordernum='{$orderid}' where id='{$arrdata[0]['id']}'");
            }
            cookie('wxzfNum',1);
        }else{
            redirect(U('BbqmDL/mycesuan','',false));exit;
        }

        $price=cookie('price');
        $price*=100;

        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $ip=preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
        $scene_info="{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://www.yixueqm.com\",\"wap_name\": \"知命支付\"}}";


        $noncestr=noncestr(15);
        $MCHID=C('GMCHID');
        $body=$name;
        $type='MWEB';
        $notifyUrl="https://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-BbqmDL-notify_url";
        $stringA="appid=".cookie('APPID')."&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&out_trade_no={$orderid}&scene_info={$scene_info}&spbill_create_ip={$ip}&total_fee={$price}&trade_type={$type}";
        $stringSignTemp=$stringA."&key=".cookie('wxKEY'); //注：key为商户平台设置的密钥key
        $sign=strtoupper(md5($stringSignTemp));

        $strData=array(
            'appid'=>cookie('APPID'),
            'mch_id'=>$MCHID,
            'nonce_str'=>$noncestr,
            'sign'=>$sign,
            'body'=>$body,
            'out_trade_no'=>$orderid,
            'total_fee'=>$price,
            'spbill_create_ip'=>$ip,
            'notify_url'=>$notifyUrl,
            'trade_type'=>$type,
            'scene_info'=>$scene_info,
        );
        $xml = "<xml>";
        foreach ($strData as $key=>$val)//数组转xml
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        $strData=$xml;
        //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
        $headers=array(
            'Content-Type:text/xml;charset=utf-8',
        );
        $url="https://api.mch.weixin.qq.com/pay/unifiedorder";

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
        $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);

        $xmlstring = simplexml_load_string($json, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        curl_close($ch);
        $redirect_url='https://'.$_SERVER['HTTP_HOST']."/zhiming/index.php/Home-BbqmDL-return_url?orderid={$orderid}&csName={$csName}";
        $redirect_url=urlencode($redirect_url);

        header("location:".$val['mweb_url']."&redirect_url=".$redirect_url);
    }
    public function wxgzhzf($nick,$name,$orderid){
        if(empty($nick)){echo 'nike';exit;}
        $arrdata=M()->query("select id from sm_h5test_bbqm where ordernum='{$orderid}' and status=-1 limit 1");
        if(!empty($arrdata)){
            if(cookie('wxzfNum')!=''){
                $orderid=$nick.date('Ymd').mt_rand(1000,9999).date('His');//重新生成订单
                cookie('orderid',$orderid);
                M()->query("update sm_h5test_bbqm set ordernum='{$orderid}' where id='{$arrdata[0]['id']}'");
            }
            cookie('wxzfNum',1);
        }else{
            redirect(U('BbqmDL/mycesuan','',false));exit;
        }

        $price=cookie('price');
        if(empty($price)){$price=68;}
        $price*=100;

        $noncestr=noncestr(15);
        $MCHID=C('GMCHID');
        $body=$name;
        $notifyUrl="https://{$_SERVER['HTTP_HOST']}/zhiming/index.php/Home-BbqmDL-notify_url";
        $stringA="appid=".cookie('APPID')."&body={$body}&mch_id={$MCHID}&nonce_str={$noncestr}&notify_url={$notifyUrl}&openid=".cookie("openid")."&out_trade_no={$orderid}&spbill_create_ip={$_SERVER['REMOTE_ADDR']}&total_fee={$price}&trade_type=JSAPI";
        $stringSignTemp=$stringA."&key=".cookie('wxKEY'); //注：key为商户平台设置的密钥key
        $sign=strtoupper(md5($stringSignTemp));

        $strData=array(
            'appid'=>cookie('APPID'),
            'mch_id'=>$MCHID,
            'nonce_str'=>$noncestr,
            'sign'=>$sign,
            'body'=>$body,
            'out_trade_no'=>$orderid,
            'total_fee'=>$price,
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$notifyUrl,
            'trade_type'=>'JSAPI',
            'openid'=>cookie("openid"),
        );

        $xml = "<xml>";
        foreach ($strData as $key=>$val)//数组转xml
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        $strData=$xml;
        //$json=json_encode($data,JSON_UNESCAPED_UNICODE);
        $headers=array(
            'Content-Type:text/xml;charset=utf-8',
        );
        $url="https://api.mch.weixin.qq.com/pay/unifiedorder";

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
        return $json;
        curl_close($ch);
    }

    public function return_url(){//支付同步回调
        if($_REQUEST['out_trade_no']){
            $orderid= htmlspecialchars($_REQUEST['out_trade_no']);
        }else if($_REQUEST['orderid']){
            $orderid=$_REQUEST['orderid'];
            sleep(3);
            $orderArr=M()->query("select id from sm_h5test_bbqm where ordernum='{$orderid}' and status=1");
            if($orderArr[0]['id']==''){
                sleep(3);
                $orderArr=M()->query("select id from sm_h5test_bbqm where ordernum='{$orderid}' and status=1");
            }
        }
        sleep(3);
        $orderArr=M()->query("select id from sm_h5test_bbqm where ordernum='{$orderid}' and status=1");
        $strData=mb_substr($orderid,2,2);
        $typeid=intval($strData);
        if($orderArr[0]['id']){
            redirect(U('BbqmDL/jieguoye','',false));
            //header('location:https://www.yixueqm.com/zhiming/index.php/Home-BbqmDL-jieguoye');
        }else{
            redirect(U('BbqmDL/mycesuan','',false));
            //header("location:https://www.yixueqm.com/zhiming/index.php/Home-BbqmDL-mycesuan");
        }
        echo '跳转失败，请返回查看';
    }
    public function notify_url(){//支付异步回调
        if ($_REQUEST['orderid']) {
            //$ordernum = $_REQUEST['orderid'];
            $paykind=0;
        }else if($_REQUEST['out_trade_no']){//支付宝
            $ordernum=$_REQUEST['out_trade_no'];
            $paykind=1;
            $appId=$_REQUEST['app_id'];//商家appID
            if($appId!='2016101302144443'){
                exit;
            }
        }else{
            $strData = $GLOBALS["HTTP_RAW_POST_DATA"];//接收到xml数据
            $obj = simplexml_load_string($strData);//把xml字符串解析成对象
            $ordernum = $obj->out_trade_no;
            $paykind=0;
        }
        $orderArr=M()->query("select id,status from sm_h5test_bbqm where ordernum='{$ordernum}' limit 1");
        if($orderArr[0]['status']!=1){
            $updateTime=date("Y-m-d H:i:s");
            M()->query("update sm_h5test_bbqm set status=1,paykind='{$paykind}',updatetime='{$updateTime}' where ordernum='{$ordernum}'");
        }
    }

}